import codecs

# 打开文件保存映射表
with open("utf8_to_gbk_table.c", "w", encoding="utf-8") as f:
    f.write("#include <stdint.h>\n\n")
    f.write("const uint16_t utf8_to_gbk_table[][2] = {\n")

    # 遍历所有可能的 Unicode 字符（0x0000 到 0xFFFF）
    for code_point in range(0x0000, 0xFFFF + 1):
        try:
            # 将 Unicode 码点转换为 UTF-8 编码
            utf8_char = chr(code_point).encode("utf-8")
            # 将 Unicode 码点转换为 GBK 编码
            gbk_char = chr(code_point).encode("gbk")

            # 如果 GBK 编码是双字节（GBK 编码范围：0x8140 到 0xFEFE）
            if len(gbk_char) == 2:
                gbk_code = (gbk_char[0] << 8) | gbk_char[1]
                # 将 UTF-8 编码转换为整数
                if len(utf8_char) == 3:
                    utf8_code = (utf8_char[0] << 16) | (utf8_char[1] << 8) | utf8_char[2]
                elif len(utf8_char) == 2:
                    utf8_code = (utf8_char[0] << 8) | utf8_char[1]
                else:
                    utf8_code = utf8_char[0]

                # 写入映射表
                
                f.write(f"    {{0x{utf8_code:04X}, 0x{gbk_code:04X}}}, // {chr(code_point)}\n")
        except UnicodeEncodeError:
            # 忽略无法编码的字符
            pass

    f.write("};\n")
    print("Mapping table generated successfully!")